package com.stone.framework.push.websocket;

import java.security.Principal;
import java.util.Map;
import java.util.Optional;

import org.springframework.http.HttpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import com.stone.framework.core.exception.BusinessException;
import com.stone.framework.core.util.Jwts;

public class AuthInboundChannelInterceptor implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            String authorization = accessor.getFirstNativeHeader(HttpHeaders.AUTHORIZATION);
            String token = Optional.ofNullable(authorization)
                .orElseThrow(() -> new BusinessException("Header 'Authorization' is null")).replace("Bearer ", "");
            Map<String, Object> map = Jwts.getPayload(token);
            String username = map.get("name").toString();
            accessor.setUser(new UserPrincipal(username));
        }
        return message;
    }

    private static class UserPrincipal implements Principal {

        private String principal;

        public UserPrincipal(String principal) {
            this.principal = principal;
        }

        @Override
        public String getName() {
            return principal;
        }

        @Override
        public String toString() {
            return principal;
        }

    }

}
